package com.asktgapp.user.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.model.CollectionVO;
import com.asktgapp.model.IndustryInfoVO;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.user.activity.IndustryInfoDetailActivity;
import com.asktgapp.utils.ImageDisplayUtil;
import com.asktgapp.widget.RefreshRecyclerView;
import com.asktgapp.modulebase.common.adapter.BaseAdapter;
import com.asktgapp.modulebase.common.adapter.BaseViewHolder;

import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018/1/9
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:
 */

public class CollectionFragment extends BaseFragment {

//    @InjectView(R.id.recycle)
    RefreshRecyclerView mRefreshRecyclerView;
    private RecyclerView mRecyclerView;
    private BaseAdapter mBaseAdapter;
    private int mPage = 1;

    private int isCollected = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_my_collection, container, false);
        ButterKnife.inject(this, viewGroup);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        getBaseActivity().setBackNavigationIcon();
        mRefreshRecyclerView=rootView.findViewById(R.id.recycle);
        mRecyclerView = mRefreshRecyclerView.getRecyclerView();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));

        mBaseAdapter = new BaseAdapter(getActivity()) {

            @Override
            public int getItemViewType(int position) {
                CollectionVO bean = (CollectionVO) mBaseAdapter.getData().get(position);
                if ( bean.getBannerPic().size() >1) {
                    return 20;
                } else {
                    return 10;
                }
            }

            @Override
            public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
                BaseViewHolder holder;

                if (viewType == 10) {
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_industry_information, parent, false), new BaseViewHolder.Callbacks() {
                        @Override
                        public void bind(BaseViewHolder holder, Object data) {
                            ImageView img = holder.getView(R.id.iv_industry_img);
                            TextView title = holder.getView(R.id.tv_industry_title);
                            TextView time = holder.getView(R.id.tv_industry_time);
                            TextView comment = holder.getView(R.id.tv_industry_read_number);
                            TextView like = holder.getView(R.id.tv_industry_like);
                            if (data instanceof CollectionVO) {
                                CollectionVO bean = (CollectionVO) data;
                                ImageDisplayUtil.LoadNetImage(img, getActivity(), bean.getBannerPic().get(0));
                                title.setText(bean.getTitle());
                                time.setText(Utils.getDateMD(bean.getAddTime()));
                                comment.setText(String.valueOf(bean.getCommentNumber()));
                                comment.setVisibility(View.VISIBLE);
                                like.setText(String.valueOf(bean.getLikeNumber()));
                                holder.getView(R.id.lookNumber).setVisibility(View.GONE);
                            }
                        }

                        @Override
                        public void onItemClick(View view, int position) {
                            CollectionVO bean = (CollectionVO) mBaseAdapter.getData().get(position);
                            Intent intent = new Intent(getActivity(), IndustryInfoDetailActivity.class);
                            intent.putExtra("id", bean.getId());
                            startActivity(intent);
                        }
                    });
                } else {
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_industry_information_three_image, parent, false), new BaseViewHolder.Callbacks() {
                        @Override
                        public void bind(BaseViewHolder holder, Object data) {

                            TextView title = holder.getView(R.id.tv_industry_title);
                            TextView time = holder.getView(R.id.tv_industry_time);
                            TextView comment = holder.getView(R.id.tv_industry_read_number);
                            TextView like = holder.getView(R.id.tv_industry_like);
                            ImageView ivQuestionImg1 = holder.getView(R.id.ivQuestionImg1);
                            ImageView ivQuestionImg2 = holder.getView(R.id.ivQuestionImg2);
                            ImageView ivQuestionImg3 = holder.getView(R.id.ivQuestionImg3);
                            comment.setVisibility(View.VISIBLE);
                            if (data instanceof CollectionVO) {

                                CollectionVO bean = (CollectionVO) data;

                                if(bean.getBannerPic().size()>2){
                                    ImageDisplayUtil.LoadNetImage(ivQuestionImg1, getActivity(), bean.getBannerPic().get(0));
                                    ImageDisplayUtil.LoadNetImage(ivQuestionImg2, getActivity(), bean.getBannerPic().get(1));
                                    ImageDisplayUtil.LoadNetImage(ivQuestionImg3, getActivity(), bean.getBannerPic().get(2));
                                }else {
                                    ImageDisplayUtil.LoadNetImage(ivQuestionImg1, getActivity(), bean.getBannerPic().get(0));
                                    ImageDisplayUtil.LoadNetImage(ivQuestionImg2, getActivity(), bean.getBannerPic().get(1));
                                    ivQuestionImg3.setVisibility(View.GONE);
                                }

                                title.setText(bean.getTitle());
                                time.setText(Utils.getDateMD(bean.getAddTime()));
                                comment.setText(String.valueOf(bean.getCommentNumber()));
                                like.setText(String.valueOf(bean.getLikeNumber()));
                                holder.getView(R.id.lookNumber).setVisibility(View.GONE);
                            }
                        }

                        @Override
                        public void onItemClick(View view, int position) {
                            CollectionVO bean = (CollectionVO) mBaseAdapter.getData().get(position);
                            Intent intent = new Intent(getActivity(), IndustryInfoDetailActivity.class);
                            intent.putExtra("id", bean.getId());
                            startActivity(intent);
                        }
                    });
                }
                return holder;
            }
        };
        mRecyclerView.setAdapter(mBaseAdapter);

        mRefreshRecyclerView.setLoadMoreAction(new RefreshRecyclerView.Action() {
            @Override
            public void onAction(int page) {
                mPage = page;
                getData(mPage);
            }
        });
        mRefreshRecyclerView.setRefreshAction(new RefreshRecyclerView.Action() {
            @Override
            public void onAction(int page) {
                mPage = page;
                getData(mPage);
            }
        });

    }

    private void doCollection(String id, final CollectionVO bean) {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap hashMap = new HashMap();
        hashMap.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        hashMap.put("type", 0);
        hashMap.put("id", id);
        //0取消收藏 1收藏
        hashMap.put("temp", 0);
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody> call = apiservice.collect(hashMap);
        call.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                dismissProgress();
                if (response.isSuccessful()) {
//                    if (i == 0) {
//                        isCollected = 0;
//                    } else {
//                        isCollected = 1;
//                    }
                    mBaseAdapter.removeData(bean);

                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });

    }

    @Override
    public void loadData() {
        visibleLoading();
        getData(mPage);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    public void getData(int mPage) {
        // TODO: 2018/1/9 分页网络请求
//        visibleLoading();
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        Call<ApiResponseBody<List<CollectionVO>>> call = apiservice.getMyCollect(params);
        call.enqueue(new Callback<ApiResponseBody<List<CollectionVO>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<CollectionVO>>> call, Response<ApiResponseBody<List<CollectionVO>>> response) {
                mRefreshRecyclerView.endPage();
                inVisibleLoading();
                if (response.isSuccessful()) {
                    List<CollectionVO> list = response.body().getResult();
                    if (list == null || list.size() == 0) {
                        visibleNoData();
                    } else {
                        mBaseAdapter.setData(list);
                    }
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<CollectionVO>>> call, Throwable t) {
                inVisibleLoading();
                mRefreshRecyclerView.endPage();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });
    }
}
